package cn.edu.gxnu;

import cn.edu.gxnu.TcpServer.ClientHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

/**
 * ClientHandler接口的http实现，用于处理http1.1请求
 */
public class HttpClientHandler implements ClientHandler {

    /**
     *
     * @param clientSocket 客户端套接字对象
     * @throws IOException 客户端异常断开连接
     */
    @Override
    public void handle(Socket clientSocket, TcpServer.Logger logger) throws IOException {
        String clientInfo = clientSocket.getInetAddress() + ":" + clientSocket.getPort();

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter out = new PrintWriter(
                     clientSocket.getOutputStream(), true)) {

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
//                System.out.println("收到数据: " + inputLine);
//                // 发送回显响应
//                out.println("ECHO: " + inputLine);
            }

            // 客户端正常断开连接
            logger.log("客户端断开连接: " + clientInfo);
        } catch (SocketException e) {
            // 客户端异常断开连接
            logger.log("客户端异常断开: " + clientInfo + " - " + e.getMessage());
            throw e;
        }
    }
}